﻿#region Copyright Notice
// 
// 
// Copyright (c) 2009-2010 Anindya Chatterjee
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// 
// 
// 
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Serialization.Xml;
using System.Windows.Forms;
using Event.Plugin.Configuration;

namespace DesktopNotifier.Utility
{
    public class UpdateUtil
    {
        private readonly AppConfig _config;
        private string _downloadString;
        private bool _updateAvailable;
        private bool _silent;

        public UpdateUtil(AppConfig config)
        {
            _config = config;
            SetupFileName = "";
        }

        internal string SetupFileName { get; set; }

        internal static string OldVersion
        {
            get
            {
                try
                {
                    return File.ReadAllText(Constants.VersionInfo);
                }
                catch (Exception)
                {
                    return File.ReadAllText("0.0.0.0");
                }
            }
        }

        internal static string NewVersion { get; private set; }

        public void CheckUpdate(object sender)
        {
            if (sender == null)
                _silent = true;
            var worker = new BackgroundWorker();
            worker.DoWork += WorkerDoWork;
            worker.RunWorkerAsync();
        }

        private void WorkerDoWork(object sender, DoWorkEventArgs e)
        {
            WebRequest request = WebRequest.Create(Constants.UpdateUrl);
            if (_config.UseProxy)
                request.Proxy = _config.Proxy;

            WebResponse response = request.GetResponse();

            var streamReader = new StreamReader(response.GetResponseStream());
            var sb = new List<string>();

            var readBuffer = new Char[256];
            int count = streamReader.Read(readBuffer, 0, 256);

            var str = new String(readBuffer, 0, count);
            sb.AddRange(str.Split(new[] {'\n', '\r'}));

            if (sb.Count == 3)
            {
                var currentVersion = new Version(OldVersion);
                var webVersion = new Version(sb[0]);

                if (webVersion.CompareTo(currentVersion) > 0)
                {
                    _updateAvailable = true;
                    _downloadString = sb[2];
                    SetupFileName = Path.GetFileName(sb[2]);
                    NewVersion = webVersion.ToString(4);
                }
            }
            streamReader.Close();
            response.Close();

            if (_updateAvailable)
            {
                if (MessageBox.Show("Current Ozone Version : "
                    + "\t" + OldVersion + "\n"
                    + "New Ozone Version : "
                    + "\t" + NewVersion + "\n"
                    + "\nUpdate With New Version Now?", "Ozone Update Available",
                    MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    var client = new WebClient();
                    if (_config.UseProxy)
                        client.Proxy = _config.Proxy;
                    client.DownloadFileCompleted += ClientDownloadFileCompleted;
                    string downloadPath = Constants.DownloadPath + SetupFileName;
                    client.DownloadFileAsync(new Uri(_downloadString), downloadPath, downloadPath);
                }
            }
            else if(!_silent)
            {
                MessageBox.Show("Sorry, no update is currently available.\nCheck again later.", "No Update");
            }
        }

        private void ClientDownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            var downloadPath = (e.UserState as string);
            Process.Start(downloadPath);
            XObjectSerializer<AppConfig>.WriteFile(Constants.Settings, _config, true);
            Application.Exit();
        }
    }
}